
#include <iostream>

#include <QApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QDebug>
#include <QDir>
#include <QFile>

#include "LeGerber/job.h"

#include "Application.h"

using namespace LeGerber;

void err(const QString &text);
void out(const QString &text);
QStringList readFileList(const QString &fileListPath);

// TODO: output management
//   - Default: print warnings and errors
//   - verbose (print 'processing" and 'processed'
//   - quiet mode don't print warnings or errors, just stats at the end
int main(int argc, char *argv[])
{
	Application app(argc, argv);
	Application::setApplicationName("le-gerber-parser");
	Application::setApplicationVersion("0.0");

	QCommandLineParser argParser;
	argParser.setApplicationDescription("Gerber file X & X2 parser");
	argParser.addHelpOption();
	argParser.addVersionOption();
	argParser.addOptions({
	                         {"j", "Process gerber files in parallel"},
	                         {"f", "Process a single Gerber file", "gerber-file"},
	                         {"F", "Process gerber files listed in a file", "gerber-list-file"},
	                         {"d", "Working directory (when using file list)", "dir"},
	                     });
	argParser.process(app);

	if (argParser.isSet("d"))
	{
		if (!QDir::setCurrent(argParser.value("d")))
		{
			err(QString("Cannot change to directory '%1'").arg(argParser.value("d")));
			return EXIT_FAILURE;
		}
	}

	QStringList fileNames;

	if (argParser.isSet("f"))
	{
		fileNames.append(argParser.value("f"));
	}
	else if (argParser.isSet("F"))
	{
		fileNames.append(readFileList(argParser.value("F")));
	}
	else
	{
		argParser.showHelp(EXIT_FAILURE);
	}

	QList<Job*> jobs;
	for (auto fileName: fileNames)
	{
		jobs.append(new Job(fileName, fileName + QString(".png")));
	}

	if (argParser.isSet("j"))
	{
		return app.runJobsConcurently(jobs);
	}
	else
	{
		return app.runJobsSequentially(jobs);
	}
}

QStringList readFileList(const QString &fileListPath)
{
	QFile file(fileListPath);
	if (!file.open(QFile::ReadOnly))
	{
		err(QString("Error opening '%1': %2").arg(fileListPath).arg(file.errorString()));
		exit(EXIT_FAILURE);
	}

	QByteArray data = file.readAll();
	QStringList result;
	for (auto path: data.split('\n'))
	{
		if (path.isNull() || path.isEmpty())
			continue;
		result.append(path.trimmed());
	}
	return result;
}

void err(const QString &text)
{
	std::cerr << text.toStdString() << std::endl;
}

void out(const QString &text)
{
	std::cout << text.toStdString() << std::endl;
}
